package up7.biz;

import java.io.IOException;
import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONObject;
import up7.model.FileInf;
import up7.utils.ConfigReader;
import up7.utils.PathTool;

public class PathBuilder {
	
	public PathBuilder(){}
	
	/**
	 * 获取上传路径
	 * 格式：
	 * 	webapp_name/upload
	 * @return
	 * @throws IOException
	 */
	public String getRoot() throws IOException
	{
		//前面会多返回一个"/", 例如  /D:/test/WEB-INF/, 奇怪, 所以用 substring()
		//path：D:/apache-tomcat-6.0.29/webapps/up7/WEB-INF/classes/
		String root = this.getClass().getResource("/").getPath().substring(1).replaceAll("//", "/");
		if ( !StringUtils.isBlank(root) && !root.endsWith("/"))
		{
			root = root.concat("/");    //避免 WebLogic 和 WebSphere 不一致
		}
		root = root.replace("%20", " ");//fix(2016-02-29):如果路径中包含空格,getPath会自动转换成%20
		int pos = root.lastIndexOf("WEB-INF/classes");
		//D:/apache-tomcat-6.0.29/webapps/up7/WEB-INF/classes/ =>D:/apache-tomcat-6.0.29/webapps/up7/
		
		//非打包模式：/F:/jsp/springboot/up6/target/classs/
		if(root.startsWith("/"))
		{
			root = root.substring(1,pos);
		}//打包模式
		else if(root.startsWith("file:/"))
		{
			root = root.substring("file:/".length(),pos);
		}
		else if(pos!=-1) 
		{
			root = root.substring(0,pos);
		}	

		ConfigReader cr = new ConfigReader();
		String pathSvr = cr.readString("IO.dir");
		pathSvr = pathSvr.replace("{root}", root);
		pathSvr = pathSvr.replaceAll("\\\\", "/");
		return pathSvr.trim();
	}
	public String genFolder(String uid,String id,String nameLoc) throws IOException{return "";}	
	public String genFile(String uid,FileInf f) throws IOException{return "";}
	public String genFile(String uid,String md5,String nameLoc)throws IOException{return "";}

	public String relToAbs(String path) throws IOException
	{
		String root = this.getRoot();
		root = root.replaceAll("\\\\", "/");
		path = path.replaceAll("\\\\", "/");
		if(path.startsWith("/"))
		{
			path = PathTool.combine(root, path);
		}
		return path.trim();
	}

	/**
	 * 将路径转换成相对路径
	 * @return
	 * @throws IOException
	 */
	public String absToRel(String path) throws IOException
	{
		String root = this.getRoot().replaceAll("\\\\", "/");
		path = path.replaceAll("\\\\", "/");
		path = path.replaceAll(root, "");
		return path.trim();
	}
}
